#!/bin/bash
clear

TEXT='\033[30;107;2m'
INFO='\033[97;44m'
WARNING='\033[97;43m'
ERROR='\033[97;41m'
SUCCESS='\033[97;42m'
GREEN='\033[92m'
YELLOW='\033[93m'
RESET='\033[0m'

if [ "${EUID}" -ne 0 ]; then
    echo -e "${ERROR} ERROR ${RESET}${TEXT} You need to run this script as root! ${RESET}"; exit 1
fi

IPADDR=$(wget -qO- ipv4.icanhazip.com)

read -rp "New client peer: " -e USERNAME
read -p "Active duration: " ACTIVETIME

expireDate=$(date -d "$ACTIVETIME days" +"%F")

CLIENT_PRIVKEY=$(wg genkey)
CLIENT_PUBKEY=$(echo "$CLIENT_PRIVKEY" | wg pubkey)
PRESHARED_KEY=$(wg genpsk)
PEER_PORT=$(shuf -i1024-65535 -n1)
PRIVATE_SUBNET_V4=$(head -n1 /etc/wireguard/wg0.conf | awk '{print $2}')
PRIVATE_SUBNET_MASK_V4=$(echo "$PRIVATE_SUBNET_V4" | cut -d "/" -f 2)
DOMAIN=$(head -n1 /etc/wireguard/wg0.conf | awk '{print $4}')
SERVER_PUBKEY=$(head -n1 /etc/wireguard/wg0.conf | awk '{print $5}')
CLIENT_DNS=$(head -n1 /etc/wireguard/wg0.conf | awk '{print $6}')
MTU_CHOICE=$(head -n1 /etc/wireguard/wg0.conf | awk '{print $7}')
NAT_CHOICE=$(head -n1 /etc/wireguard/wg0.conf | awk '{print $8}')
CLIENT_ALLOWED_IP=$(head -n1 /etc/wireguard/wg0.conf | awk '{print $9}')
LASTIP4=$(grep "/32" /etc/wireguard/wg0.conf | tail -n1 | awk '{print $3}' | cut -d "/" -f 1 | cut -d "." -f 4)
CLIENT_ADDRESS_V4="${PRIVATE_SUBNET_V4::-4}$((LASTIP4 + 1))"

echo "# $USERNAME $expireDate start
[Peer]
PublicKey = $CLIENT_PUBKEY
PresharedKey = $PRESHARED_KEY
AllowedIPs = $CLIENT_ADDRESS_V4/32
# $USERNAME $expireDate end" >>/etc/wireguard/wg0.conf

echo "# $USERNAME
[Interface]
Address = $CLIENT_ADDRESS_V4/$PRIVATE_SUBNET_MASK_V4
DNS = $CLIENT_DNS
ListenPort = $PEER_PORT
MTU = $MTU_CHOICE
PrivateKey = $CLIENT_PRIVKEY

[Peer]
AllowedIPs = $CLIENT_ALLOWED_IP
Endpoint = $DOMAIN$SERVER_PORT
PersistentKeepalive = $NAT_CHOICE
PresharedKey = $PRESHARED_KEY
PublicKey = $SERVER_PUBKEY" >>/etc/wireguard/clients/$USERNAME/$USERNAME.conf

echo "$USERNAME $ACTIVETIME $expireDate"

qrencode -t ansiutf8 \
-o "/etc/wireguard/clients/$USERNAME/$USERNAME.png" \
-r "/etc/wireguard/clients/$USERNAME/$USERNAME.conf"
clientCodeQR=$(cat /etc/wireguard/clients/$USERNAME/$USERNAME.png)
echo "Client config --> /etc/wireguard/clients/$USERNAME/$USERNAME.conf"
echo "Client QRcode --> /etc/wireguard/clients/$USERNAME/$USERNAME.png"

# Restart WireGuard
systemctl restart wg-quick@wg0

clear
echo
echo "========================== [ ACCOUNT DETAIL ]"
echo "  Address: $IPADDR"
echo " Hostname: $DOMAIN"
echo " Username: $USERNAME"
echo " Duration: $ACTIVETIME days"
echo "  Expired: $expireDate"
echo "---------------------------------------------"
echo "     Link: https://${DOMAIN}/${USERNAME}.conf"
echo ""
echo "$clientCodeQR"
echo "---------------------------------------------"
echo "Copyright 2021 Cybertize, Allright Reserved."
echo "============================================="
echo
